<template>
  <div :id="uuid"></div>
</template>
<script>
  import { getDomain } from "@/utils/auth";
  import PDFH5 from "pdfh5";
  import "pdfh5/css/pdfh5.css";
  import { nanoid } from "nanoid";
  export default {
    props: {
      path: {
        type: String,
        required: true,
      },
      // 新增搜索字段prop
      searchKeyword: {
        type: String,
        default: "",
      },
    },
    data() {
      return {
        uuid: "pdf" + nanoid(),
        domain: getDomain(),
        pdfh5: null,
        container: null, // 新增容器引用
        textElements: [],
        textContent: "",
      };
    },
    mounted() {
			this.$nextTick(()=>{
				this.container = document.getElementById(this.uuid);
      	this.renderPDF();
			})
    },
    beforeDestroy() {
      if (this.container) {
        this.container.removeEventListener('scroll', this.handleScroll);
      }
      if (this.pdfh5) {
        try {
          this.pdfh5.destroy();
        } catch (error) {
          console.log(error);
        }
      }
    },
    watch: {
      path() {
        this.pdfh5 && this.pdfh5.destroy();
        this.pdfh5 = null;
        document.getElementById(this.uuid).innerHTML = "";
        this.$nextTick(() => {
          this.renderPDF();
        });
      },
      // 监听搜索字段变化
      searchKeyword(newVal) {
				console.log('newVal',newVal)
        if (newVal) {
					this.clearHighlights();
          this.highlightText(newVal);
        } else {
          this.clearHighlights();
        }
      },
    },
    methods: {
      renderPDF() {
        // console.log('this.path',this.path)
        if (this.path && this.path.length > 0) {
          const pdfurl = (process.env.NODE_ENV === "development" ? "/previewPDF" : this.domain) + this.path;
          // 在PDFH5配置中增加缩放回调
          this.pdfh5 = new PDFH5(document.querySelector("#" + this.uuid), {
            pdfurl,
            lazy: false, // 启用懒加载（适用于多页PDF）
            renderType: "canvas", // 渲染模式：canvas或svg
            textLayer: true, // 启用文本层渲染（必须开启才能搜索）
          });
          // console.log('this.pdfh5',this.pdfh5);
          this.pdfh5.on("render", this.handleRender);
        } else {
          this.pdfh5 = null;
          document.getElementById(this.uuid).innerHTML = "";
        }
      },
      // 提取渲染处理逻辑为独立方法
      handleRender(currentNum, time, currentPageDom) {
        setTimeout(() => {
          this.textElements = currentPageDom?.querySelectorAll(".textLayer span") || [];
					// console.log(this.container.querySelector('.viewerContainer'))
					this.container.querySelector('.viewerContainer').addEventListener('scroll', this.handleScroll);
          this.$emit("render", currentPageDom);
        }, 0);
      },
      handleScroll(e) {
				console.log('e',this)
        this.$emit('scroll', this.container.scrollTop);
      },
      highlightText(keyword = '') {
        if (!keyword) return this.clearHighlights();
        
        const escapedKeyword = keyword.replace(/[\^$.*+?()[\]{}|]/g, '\\$&');
        const regex = new RegExp(escapedKeyword, 'gi');
        
        const highlights = [];
        Array.from(this.textElements).forEach((element) => {
          const text = element.textContent;
          if (regex.test(text)) {
            element.innerHTML = text.replace(regex, `<span class="pdf-highlight">$&</span>`);
            highlights.push(element);
          }
        });

        if (highlights.length > 0) {
          const rect = highlights[0].getBoundingClientRect();
					const viewerContainer = this.container.querySelector('.viewerContainer');
					const viewerContainerRect = viewerContainer.getBoundingClientRect();

					if (rect.top < viewerContainerRect.top || rect.bottom > viewerContainerRect.bottom) {
            const scrollTop = viewerContainer.scrollTop + rect.top - viewerContainerRect.top - 50;
						viewerContainer.scrollTo({
              top: scrollTop,
              behavior: 'smooth'
            });
          }
        }
      },
      // 新增清除高亮方法
      clearHighlights() {
        this.textElements?.forEach((element) => {
          element.innerHTML = element.textContent;
        });
      },
    },
  };
</script>
<style lang="scss">
  .pdf-highlight {
    position: relative;
    background-color: red;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  .pdf-highlight.active {
    background-color: red;
  }
</style>
